package com.lenovo.lcdm.dcm.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lenovo.lcdm.common.enums.DeleteFlagEnum;
import com.lenovo.lcdm.dcm.dto.ItsmAuthItemDto;
import com.lenovo.lcdm.dcm.dto.ItsmAuthReturnDto;
import com.lenovo.lcdm.dcm.dto.ItsmAuthsDto;
import com.lenovo.lcdm.dcm.entity.ItsmAuthRequest;
import com.lenovo.lcdm.dcm.service.ItsmAuthRequestService;
import com.lenovo.lcdm.integration.config.ConsumerMessageHandler;
import com.lenovo.lcdm.integration.utils.KafkaHelper;
import com.lenovo.lcdm.team.dto.UserDto;
import com.lenovo.lcdm.team.entity.TeamUser;
import com.lenovo.lcdm.team.enums.LoginTypeEnum;
import com.lenovo.lcdm.team.service.ITeamUserService;
import com.lenovo.lcdm.team.vo.GroupVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class ItsmUserRequestConsumerHandler implements ConsumerMessageHandler {
    @Override
    public void handleMessage(String msg){
        ITeamUserService userService = SpringUtil.getBean(ITeamUserService.class);
        ItsmAuthRequestService itsmAuthRequestService = SpringUtil.getBean(ItsmAuthRequestService.class);

        JSONObject jsonObject = JSONUtil.parseObj(msg);
        
        String targetSystem = String.valueOf(jsonObject.get("targetSystem"));
        if(StringUtils.isEmpty(targetSystem) || !targetSystem.equals("NPIP")){
            return;
        }
        //parse userInfo
        JSONObject userInfoObject = JSONUtil.parseObj(jsonObject.get("userInfo"));
        String itCode = String.valueOf(userInfoObject.get("userId"));
        ItsmAuthRequest itsmAuthRequest = new ItsmAuthRequest();
        String worderId = String.valueOf(jsonObject.get("worderId"));
        itsmAuthRequest.setWorderId(worderId);
        itsmAuthRequest.setRequestorId(String.valueOf(jsonObject.get("requestorId")));
        itsmAuthRequest.setRequestReason(String.valueOf(jsonObject.get("requestReason")));
        itsmAuthRequest.setRequestedDate(String.valueOf(jsonObject.get("requestedDate")));
        itsmAuthRequest.setUserId(itCode);

        JSONArray authsObject = JSONUtil.parseArray(jsonObject.get("auths"));
        List<ItsmAuthItemDto> authList = JSONUtil.toList(authsObject, ItsmAuthItemDto.class);

        ItsmAuthsDto itsmAuthsDto = new ItsmAuthsDto();
        itsmAuthsDto.setAuths(authList);
        log.info("--ItsmUserRequestConsumerHandler start: worderId-{}, userId-{}.", worderId, itCode);
        // 组装Group的add列表和remove列表
        List<String> addList = new ArrayList();
        List<String> removeList = new ArrayList();
        Set<String> resultSet = new HashSet();
        for(ItsmAuthItemDto item : authList){
            if(item.getItemType().equals("GROUP")){
                if(item.getType().equals("ADD")){
                    addList.add(item.getItemName());
                }else if(item.getType().equals("REMOVE")){
                    removeList.add(item.getItemName());
                }
            }
        }

        // 检查itcode是否在系统已存在
        QueryWrapper<TeamUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("it_code", itCode);
        queryWrapper.eq("deleted", DeleteFlagEnum.NO.getValue());
        TeamUser user = userService.getOne(queryWrapper);

        UserDto userDto = new UserDto();
        userDto.setItCode(itCode);
        userDto.setLoginType(LoginTypeEnum.REMOTE.getType());
        List<GroupVo> oldGroups = null;
        // 如果用户不存在，只增加add权限；否则，用原Group列表+add列表-remove列表
        if (user != null) {
            userDto.setId(user.getId());
            oldGroups = userService.getUserGroups(user.getItCode());
            resultSet.addAll(addList);
            if (CollectionUtil.isNotEmpty(oldGroups)) {
                resultSet.addAll(oldGroups.stream().map(GroupVo::getGroupName).collect(Collectors.toSet()));
            }
            resultSet.removeAll(removeList);
        }else{
            resultSet = addList.stream().collect(Collectors.toSet());
        }
        userDto.setGroupNames((resultSet));
        String state = "FAILED";
        try {
            // 保存或更新用户，保存权限组
            userService.saveUser(userDto);
            state = "SUCCEED";
            // 保存申请记录
            itsmAuthRequest.setState(state);
            itsmAuthRequestService.save(itsmAuthRequest);
            sendReturnMsg(worderId, state, state);
            log.info("--request auth succeed.");
        }catch (Exception e){
            log.info("--request auth failed, {}", e.getMessage());
            // 保存申请记录
            itsmAuthRequest.setState(state);
            itsmAuthRequestService.save(itsmAuthRequest);
            sendReturnMsg(worderId, state, e.getMessage());
            throw e;
        }
    }

    private void sendReturnMsg(String worderId, String state, String message){
        // 返回kafka消息
        ItsmAuthReturnDto itsmAuthReturnDto = new ItsmAuthReturnDto();
        itsmAuthReturnDto.setWorderId(worderId);
        itsmAuthReturnDto.setStatus(state);
        itsmAuthReturnDto.setMsg(message);
        KafkaHelper.publish("itsm-auth-request-result",  JSONUtil.toJsonStr(itsmAuthReturnDto));
    }
}
